package br.sales.view.util;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.db4o.ObjectContainer;

public class ViewUtil {
	
	public static final String CALLBACK_CLOSE = "close";
	public static final String OBJECT_CONTAINER = "objectContainer";
	public static final String REQUEST_OBJECT_CONTAINER = "requestContainer"; 
	
	public static void addMessage(FacesContext context, String message, Severity severity){
		FacesMessage facesMessage = new FacesMessage(severity, message, null); 
		FacesContext.getCurrentInstance().addMessage(null, facesMessage);
	}
	
	public static void addMessage(FacesContext context,String componentId ,String message, Severity severity){
		FacesMessage facesMessage = new FacesMessage(severity, message, null); 
		FacesContext.getCurrentInstance().addMessage(componentId, facesMessage);
	}
	
	public static String getResourceBundle(FacesContext context, String key){
		String toReturn = key;
		try{
		ResourceBundle resourceBundle = ResourceBundle.getBundle(context.getApplication().getMessageBundle(),context.getViewRoot().getLocale());
		toReturn = resourceBundle.getString(key);
		}catch (MissingResourceException  e) {
			e.printStackTrace();
		}
		return toReturn;
	}
	
	public static Object getManagedBean(FacesContext context, String beanName, Class beanClass){
		Object managedBean = null;
		
		if (context != null){
			try {
			managedBean = context.getApplication().getExpressionFactory().createValueExpression(context.getELContext(),
							"#{"+beanName+"}", beanClass).getValue(context.getELContext());
			} catch (Exception e) {
				e.printStackTrace();
				managedBean = null;
			}
		}
		
		return managedBean;
	}
	
	public static Object getComponentById(FacesContext context, String componentId){
		return componentId;
	}
	
	public static String getSessionId(){
		return ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).getId();
	}
	
	public static ObjectContainer getRequestObjectContainer(){
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		ObjectContainer objectContainer = (ObjectContainer) request.getAttribute(REQUEST_OBJECT_CONTAINER);
		return objectContainer;
	}
	
}
